﻿/**************************************************************************
创建日期:	2020/1/3
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com
创建时间:	
Copyright (c)    ZhCun.cn

描	述：
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Management;

namespace ASmile.Helpers
{
    /// <summary>
    /// 获取本地计算机的相关信息
    /// </summary>
    public class HostHelper
    {
        /// <summary>
        /// 获取本地计算机名称
        /// </summary>
        public static string GetHostName()
        {
            string hostName = Dns.GetHostName();
            return hostName;
        }
        /// <summary>
        /// 获取ip地址，根据索引获取哪个IP，默认为最后一个，即本机的网卡IP
        /// </summary>
        public static string GetIp(int ipIndex = -1)
        {
            var hostName = GetHostName();
            IPAddress[] ips = Dns.GetHostAddresses(hostName);
            if (ips == null || ips.Length == 0)
            {
                return string.Empty;
            }
            if (ipIndex < 0 || ipIndex >= ips.Length)
            {
                return ips[ips.Length - 1].ToString();
            }
            else
            {
                return ips[ipIndex].ToString();
            }
        }
        /// <summary>
        /// 获取本机 IPV4 地址
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.LogObj.Error("获取本机IP出错", ex);
                return "";
            }
        }

        /// <summary>
        /// 返回描述本地计算机上的网络接口的对象(网络接口也称为网络适配器)。
        /// </summary>
        public static NetworkInterface[] NetCardInfo()
        {
            return NetworkInterface.GetAllNetworkInterfaces();
        }
        ///<summary>
        /// 通过NetworkInterface读取网卡Mac
        ///</summary>
        ///<returns></returns>
        public static List<string> GetMacByNetworkInterface()
        {
            List<string> macs = new List<string>();
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface ni in interfaces)
            {
                macs.Add(ni.GetPhysicalAddress().ToString());
            }
            return macs;
        }

#if NET40
        ///<summary>
        /// 通过WMI读取系统信息里的网卡MAC
        ///</summary>
        public static List<string> GetMacByWMI()
        {
            List<string> macs = new List<string>();
            try
            {
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"])
                    {
                        
                        mac = mo["MacAddress"].ToString();
                        macs.Add(mac);
                    }
                }
                moc = null;
                mc = null;
            }
            catch(Exception ex)
            {
                LogHelper.LogObj.Error("获取Mac地址失败", ex);
            }

            return macs;
        }


        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(int dest, int host, ref long mac, ref int length);
        [DllImport("Ws2_32.dll")]
        private static extern int inet_addr(string ip);
        ///<summary>
        /// 通过SendARP获取网卡Mac
        /// 网络被禁用或未接入网络（如没插网线）时此方法失灵
        ///</summary>
        public static string GetMacBySendARP(string remoteIP)
        {
            StringBuilder macAddress = new StringBuilder();
            try
            {
                int remote = inet_addr(remoteIP);
                long macInfo = 0;
                int length = 6;
                SendARP(remote, 0, ref macInfo, ref length);
                string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
                int x = 12;
                for (int i = 0; i < 6; i++)
                {
                    if (i == 5)
                    {
                        macAddress.Append(temp.Substring(x - 2, 2));
                    }
                    else
                    {
                        macAddress.Append(temp.Substring(x - 2, 2) + "-");
                    }
                    x -= 2;
                }
                return macAddress.ToString();
            }
            catch
            {
                return macAddress.ToString();
            }
        }


#endif

    }
}